'use strict';
const Service = require('egg').Service;
const fs = require("fs");
const path = require("path");
const  UUID = require('uuid');

// 1、uuid.v1(); -->基于时间戳生成  （time-based）
// 2、uuid.v4(); -->随机生成  (random)
function GetUUID(){
    let res = UUID.v4();
    return res.replace(/-/g,"");
}

console.log(GetUUID());
function removeImg(name){
    let p = path.join(__dirname,`../public/upload/${name}`);
    try{
        fs.unlink(p,function(er){
            if(er){
                console.log("删除文件失败",p);
            }
        });
    }catch(e){
        console.log("删除失败",p)
    }
}




class FormService extends Service {
    async save(opt){
        const {ctx,app,service} = this;
        let formHead = opt.M || {};
        if(formHead._id){
            let id = formHead._id;
            // 是更新
            delete formHead._id;
            await  ctx.model.FormHead.updateOne({_id:formHead._id},{$set:formHead});
            formHead._id = id;
        }else{
            let  add = await new ctx.model.FormHead(formHead).save();
            formHead = JSON.parse(JSON.stringify(add));
        }
        let  formBodys = opt.F || [];
        let hasId = []
        let FORMID = formHead._id;
        for(let i = 0; i < formBodys.length; i++){
            let item = formBodys[i];
            let obj = {
                FORMID:FORMID,
                F:item
            }
            if(item._id){
                hasId.push(ctx.model.FormBody.updateOne({"_id":item._id},{"$set":obj}));
            }else{
                hasId.push(new ctx.model.FormBody(obj).save());
            }
           
        }
        await Promise.all(hasId);
        return this.info(FORMID);  
    }
    async remove(id){
        // 删除表头
        await this.ctx.model.FormHead.deleteOne({"_id":id})
        // 删除组件
        await this.ctx.model.FormBody.deleteOne({"FORMID":id});

        // 删除数据

        return "删除成功";
    }
    
    async list(opt,uid){
        let pageSize = parseInt(opt.pageSize) || 20; //每页多少条
        let pageNum = parseInt(opt.pageNum) || 1; //多少页
        let skip = (pageNum - 1) * pageSize;
        let orderby = opt.orderby;
        if(orderby !== "FRMNM"){
            orderby = "updatedAt";
        }

        delete opt.pageSize;
        delete opt.pageNum;
        delete opt.orderby;
        
        let or = [];
        for(let i in opt){
            if(opt[i]){
                or.push({
                    [i]:opt[i]
                })
            }
        }
        let search = {uid};
        if(or.length > 0){
            search["$or"] = or;
        }
        let sort = {};
        sort[orderby] = -1;

        let list = await this.ctx.model.FormHead.find(search).sort(sort).skip(skip).limit(pageSize);
        let count = await this.ctx.model.FormHead.find(search).countDocuments();
        return Promise.resolve({list,count,pageSize,pageNum});
    }
    async info(id){
        const {ctx,app} = this;
        let formHead = await ctx.model.FormHead.findOne({"_id":id});
        if(!formHead){
            return Promise.reject("表单不存在");
        }
        let M = JSON.parse(JSON.stringify(formHead));
        let formBodys = await ctx.model.FormBody.find({"FORMID":M._id})
        formBodys = formBodys || [];
        formBodys = JSON.parse(JSON.stringify(formBodys));
         let F = [];
         for(let i = 0; i < formBodys.length; i++){
             let item = formBodys[i];
             item.F._id = item._id;
             F.push(item.F);
         }
        return Promise.resolve({M,F});
    }
    async submit(opt){
        // 提交数据
        if(!opt.FORMID || !opt.DATA){
            return Promise.reject(app.resCode.params);
        }
        return new this.ctx.model.FormData(opt).save();
    }
    async removeData(id){
        // 删除数据
        if(!id){
            return Promise.reject(app.resCode.params);
        }
        return this.ctx.model.FormData.deleteOne({"_id":id});
    }
    async infoData(id){
        return  this.ctx.model.FormData.findOne({"_id":id});
    }
    async listData(opt){
        let pageSize = parseInt(opt.pageSize) || 20; //每页多少条
        let pageNum = parseInt(opt.pageNum) || 1; //多少页
        let FORMID = opt.FORMID;
        let skip = (pageNum - 1) * pageSize;
        let orderby = "updatedAt";
        delete opt.pageSize;
        delete opt.pageNum;
        delete opt.orderby;
        delete opt.FORMID;
        let or = [];
        for(let i in opt){
            if(opt[i]){
                or.push({
                    [i]:opt[i]
                })
            }
        }
        let search = {FORMID};
        if(or.length > 0){
            search["$or"] = or;
        }
        let sort = {};
        sort[orderby] = -1;
        let list = await this.ctx.model.FormData.find(search).sort(sort).skip(skip).limit(pageSize);
        let count = await this.ctx.model.FormData.find(search).countDocuments();
        return Promise.resolve({list,count,pageSize,pageNum});
    }
}

module.exports = FormService;